/*
 抓取 http://quote.eastmoney.com/concept/SZ300059.html?from=data
 开盘、收盘、最高、最低、成交量、成交额、振幅、换手率
 klt=101 日线 / 102 周线 / 103 月线 / 5 5min / 15 15min
 fqt: 0 不复权 / 1 前复权 / 2 后复权
 嵌入iframe K线页面
 http://quote.eastmoney.com/basic/h5chart-iframe.html?code=300059&market=2&type=r
 板块涨幅
 http://push2.eastmoney.com/api/qt/clist/get?cb=jQuery1124042420171768027837_1594138138399&pn=1&pz=20&po=1&np=1&fltt=2&invt=2&fid=f3&fs=m:90+t:2+f:!50&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f26,f22,f33,f11,f62,f128,f136,f115,f152,f124,f107,f104,f105,f140,f141,f207,f208,f209,f222&_=1594138138409
 相关板块
 http://push2.eastmoney.com/api/qt/slist/get?spt=3&pi=0&po=1&invt=2&fields=f14,f3,f128,f12,f13,f100,f102,f103&secid=0.300059&cb=jQuery112409294279976772082_1594136922130&_=1594136922175
 分时线
 http://push2his.eastmoney.com/api/qt/stock/trends2/get?cb=time&fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13&fields2=f51,f52,f53,f54,f55,f56,f57,f58&ndays=5&iscr=0&secid=0.300059
*/
function getStockData(key, period, dataLimit, endDate, real) {
    function getStockId(id) {
        var header = {
            "0" : "0.",
            "1" : "0.",
            "2" : "0.",
            "3" : "0.",
            "5" : "1.",
            "6" : "1.",
            "9" : "1.",
            "4" : ""
        };
        return (header[id.slice(0,1)] || "") + id;
    }

    var dtd = $.Deferred();
    period = period || 101;
    dataLimit = dataLimit || 120;
    endDate = endDate || "20500101";
    key.index = [key.id, period, dataLimit].join();

    function get() {
        var stockId = getStockId(key.id);
        $.ajax({
            url: "http://push2his.eastmoney.com/api/qt/stock/kline/get?cb=stockData&fields1=f1,f2,f3,f4,f5,f6&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f61&klt="
                + period + "&fqt=1&secid=" + stockId + "&end=" + endDate + "&lmt=" + dataLimit,
            dataType: "text"
        }).then(function (response) {
            var out = [];
            function stockData(response) {
                var arr = response.data.klines;
                for (var i in arr) {
                    try {
                        var o = arr[i].split(",");
                        out.push({
                            time: o[0],
                            open: parseFloat(o[1]),
                            close: parseFloat(o[2]),
                            high: parseFloat(o[3]),
                            low: parseFloat(o[4]),
                            volume: parseFloat(o[5]),
                            transactions: Math.round(parseFloat(o[6]) / 10000),
                            amplitude: parseFloat(o[7]),
                            turnover: parseFloat(o[8]),
                        });
                    } catch (e) {
                        console.log(e, i, arr[i])
                    }
                }
            }

            eval(response);
            key.data = out;
            DB.setTableRow("source", key);
            dtd.resolve(key);
        }, function () {
            dtd.reject();
        });
    }

    if (real) {
        get();
    } else {
        DB.getTableRow("source", key.index).then(function (data) {
            dtd.resolve(data);
        }).catch(get);
    }
    return dtd.promise();
}

function fetchStockList(query_str) {
    var dtd1 = $.Deferred();
    var dtd2 = $.Deferred();
    var dtd3 = $.Deferred();

    $.ajax({
        url: "http://m.iwencai.com/unified-wap/get-base-data?&w=" + query_str,
        dataType: "jsonp",
        processData: false,
        type: 'get',
        jsonpCallback: "callCond",
        xhrFields: {
            withCredentials: true
        }
    }).done(function (response) {
        console.log(response);
        var out = {
            query: query_str,
            condition: encodeURIComponent(JSON.stringify(response.data.condition))
        };
        dtd1.resolve(out);
        return dtd1.promise();
    }).fail(function () {
        dtd1.reject();
        dtd2.reject();
        dtd3.reject();
    });

    dtd1.done(function (cond) {
        console.log(cond);
        return $.ajax({
            url: "http://m.iwencai.com/unified-wap/get-parser-data?w=" + cond.query + "&condition=" + cond.condition,
            dataType: "jsonp",
            type: 'get',
            jsonpCallback: "callParse",
            processData: false
        }).done(function (response) {
            console.log(response);
            var out = {
                total: response.data.analyze_data.total,
                token: response.data.token
            };
            dtd2.resolve(out);
            return dtd2.promise();
        });
    }).fail(function () {
        dtd2.reject();
        dtd3.reject();
    });

    dtd2.done(function (cond) {
        console.log(cond);
        return $.ajax({
            url: "http://m.iwencai.com/unified-wap/cache?page=0&perpage=" + cond.total + "&token=" + cond.token,
            dataType: "jsonp",
            type: 'get',
            jsonpCallback: "callAll",
            processData: false
        }).then(function (response) {
            console.log(response);
            var out = [];
            var _wencai_stock = response.data.data;
            for (var i in _wencai_stock) {
                var key = _wencai_stock[i];
                if (key) {
                    var info = {
                        id: key['hqCode'],
                        name: key['股票简称'] || key['基金简称'],
                        index: (key['所属概念'] || "").split(/;|；/img),
                        new_price: key['最新价'] || key['基金@最新单位净值']
                    };
                    out.push(info);
                }
            }
            console.log(["callAll 问财数据", _wencai_stock, out]);
            dtd3.resolve(out);
        });
    }).fail(function () {
        dtd3.reject();
    });

    return dtd3.promise();
}

function getUrl(id) {
    function getMarketId(id) {
        const header = {
            "0": "2",
            "1": "2",
            "2": "2",
            "3": "2",
            "5": "1",
            "6": "1",
            "9": "1",
            "4": ""
        };
        var market = header[id.slice(0, 1)] || "2";
        return market + "." + id;
    }
    return "https://wap.eastmoney.com/quote/stock/" + getMarketId(id) + ".html";
}